﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DIProject.ReceptionGoods
{	public partial class SupplierReturnParties : Form
	{	private	StringBuilder autoSearchBuffer = new StringBuilder(128);
		private	int autoSearchColumn = 0;
		public System.Windows.Forms.BindingSource PartiesBindingSource{get{return supplierReturnPartiesBindingSource;}}
//-------------------------------------------------------------------------------------------------
	/// <summary>Признак автоматического поиска</summary>
		public	bool AutoSearch
		{	get{return autoSearch;}
			set{autoSearch = value;}
		}
		private	bool autoSearch = true;
//-------------------------------------------------------------------------------------------------
	/// <summary>Задержка в секундах перед обнулением буфера поиска между нажатиями клавиш при автоматическом поиске</summary>
		public	int AutoSearchDelay
		{	get{return autoSearchDelay;}
			set
			{	bool running = timerAutoSearch.Enabled;
				if(running)
					timerAutoSearch.Stop();
				autoSearchDelay = value;
				timerAutoSearch.Interval = autoSearchDelay*1000;
				if(running)
					timerAutoSearch.Start();
			}
		}
		private	int autoSearchDelay = 2;
//-------------------------------------------------------------------------------------------------
		private void timerAutoSearch_Tick(object sender, EventArgs e)
		{	textBoxName.Hide();
			autoSearchBuffer.Length = 0;
			timerAutoSearch.Stop();
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		public	DIProject.DataSets.waybillsData.SupplierReturnPartiesRow CurrentRow
		{	get{return partiesGridView.CurrentCell != null? (DIProject.DataSets.waybillsData.SupplierReturnPartiesRow)((DataRowView)partiesGridView.CurrentCell.OwningRow.DataBoundItem).Row: null;}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private	int? partyId = null;
		private	bool checkRest = true;
		private	int supplierId = 0;
//-------------------------------------------------------------------------------------------------
		public SupplierReturnParties() : this(null, true, 0)
		{
		}
		public SupplierReturnParties(int? partyId, bool checkRest, int supplierId)
		{	InitializeComponent();
			textBoxName.Hide();
			timerAutoSearch.Interval = autoSearchDelay*1000;
			this.partyId		= partyId;
			this.checkRest		= checkRest;
			this.supplierId		= supplierId;
		}
//-------------------------------------------------------------------------------------------------
		private void SupplierReturnParties_Load(object sender, EventArgs e)
		{	int rowIndex;
			DIProject.DataSets.Dictionary.PartiesRow row;
			try
			{	supplierReturnPartiesTableAdapter.Fill(waybillsData.SupplierReturnParties, supplierId);//, null, checkRest);
			//	if(partyId != null
			//	&& (row = waybillsData.SupplierReturnParties.FindById((int)partyId)) != null
			//	&& (rowIndex = waybillsData.SupplierReturnParties.Rows.IndexOf(row)) >= 0)
			//		partiesGridView.CurrentCell = partiesGridView[nameDataGridViewTextBoxColumn.Index, rowIndex];
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			DialogResult = DialogResult.None;
		}
//-------------------------------------------------------------------------------------------------
		private void SupplierReturnParties_FormClosed(object sender, FormClosedEventArgs e)
		{	timerAutoSearch.Stop();
			textBoxName.Hide();
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void partiesGridView_KeyDown(object sender, KeyEventArgs e)
		{	if(e.KeyCode == Keys.Enter)
				e.Handled = true;
		}
//-------------------------------------------------------------------------------------------------
		private void partiesGridView_KeyPress(object sender, KeyPressEventArgs e)
		{	timerAutoSearch.Stop();
			if(e.KeyChar == ' ' || e.KeyChar == '-' || e.KeyChar == '+' || char.IsLetterOrDigit(e.KeyChar))
			{	autoSearchBuffer.Append(e.KeyChar);
				SearchRow();
			}
			else if(e.KeyChar == '\b')
			{	if(autoSearchBuffer.Length > 0)
				{	autoSearchBuffer.Remove(autoSearchBuffer.Length - 1, 1);
					SearchRow();
				}
				else
					Console.Beep();
			}
			else if(e.KeyChar == '\r')
			{	if(partiesGridView.CurrentCell != null)
					DialogResult = DialogResult.OK;
			}
			else
			{	textBoxName.Hide();
				autoSearchBuffer.Length = 0;
			}
		}
//-------------------------------------------------------------------------------------------------
		private void SearchRow()
		{	if(autoSearchColumn >= 0
			&& autoSearchColumn <  partiesGridView.Columns.Count
			&& partiesGridView.Columns[autoSearchColumn].ValueType == typeof(string))
			{	bool found = false;
				DataGridViewRow row;
				DataGridViewCell cell;
				DataGridViewRowCollection rows = partiesGridView.Rows;
				string cellText, searchText = autoSearchBuffer.ToString();
				for(int i = 0, n = rows.Count; i < n; ++i)
				{	row = rows[i];
					cell = row.Cells[autoSearchColumn];
					if(cell.Value is string)
					{	cellText = (string)cell.Value;
						if(cellText.StartsWith(searchText, StringComparison.OrdinalIgnoreCase))
						{	found = true;
							textBoxName.Hide();
							changeCurrentCell = true;
							partiesGridView.CurrentCell = row.Cells[partiesGridView.CurrentCell.ColumnIndex];
							changeCurrentCell = false;
							Rectangle rc = partiesGridView.GetCellDisplayRectangle(autoSearchColumn, i, true);
							textBoxName.AutoSize		= false;
							textBoxName.Font			= cell.Style.Font != null? cell.Style.Font: partiesGridView.Font;
							textBoxName.Location		= new Point(rc.X, rc.Y);
							textBoxName.Size			= new Size(rc.Width, rc.Height);
							textBoxName.Text			= cellText;
							textBoxName.SelectionStart	= searchText.Length;
							textBoxName.SelectionLength	= cellText.Length - searchText.Length;
							textBoxName.Show();
							break;
						}
					}
				}
				if(!found)
				{	autoSearchBuffer.Remove(autoSearchBuffer.Length - 1, 1);
					Console.Beep();
				}
				timerAutoSearch.Start();
			}
		}
//-------------------------------------------------------------------------------------------------
		private bool changeCurrentCell = false;
		private void partiesGridView_CurrentCellChanged(object sender, EventArgs e)
		{	if(!changeCurrentCell)
			{	timerAutoSearch.Stop();
				textBoxName.Hide();
				autoSearchBuffer.Length = 0;
				autoSearchColumn = partiesGridView.CurrentCell != null? partiesGridView.CurrentCell.ColumnIndex: -1;
			}
		}
//-------------------------------------------------------------------------------------------------
		private void partiesGridView_Scroll(object sender, ScrollEventArgs e)
		{	if(!changeCurrentCell)
			{	timerAutoSearch.Stop();
				textBoxName.Hide();
				autoSearchBuffer.Length = 0;
			}
		}
//-------------------------------------------------------------------------------------------------
		private void partiesGridView_MouseDoubleClick(object sender, MouseEventArgs e)
		{	DataGridView.HitTestInfo hit = partiesGridView.HitTest(e.X, e.Y);
			if(hit.Type == DataGridViewHitTestType.Cell)
			{	partiesGridView.CurrentCell = partiesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
				DialogResult = DialogResult.OK;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
	}
}